import { isArray, normalizeUrl } from '@web-utils/core'
import { server, services } from '@/config'

export const toFileUrl = file => {
  return normalizeUrl(`${server + services.adminService}sys-file/${file.bucketName}/${file.name}`)
}

/**
 * 定义表格选项
 * @param option {TableUtil.TableOption}
 * @return {TableUtil.TableOption}
 */
export const defineTableOption = option => option

export const withContext = url => {
  if (url) {
    if (url.indexOf('/') === 0) {
      return normalizeUrl(`.${url}`)
    }
    return normalizeUrl(`./${url}`)
  }
  return url
}

/**
 * 对象转 query string
 * @param obj
 * @returns {string}
 */
export function toQueryString(obj) {
  const result = []
  Object.keys(obj).forEach(ele => {
    result.push(`${ele}=${obj[ele]}`)
  })
  return result.join('&')
}

export const flatArray = array => {
  const temp = []
  if (!array) {
    return temp
  }
  if (isArray(array)) {
    array.forEach(value => {
      if (isArray(value)) {
        temp.push(...flatArray(value))
      } else {
        if (value) {
          temp.push(value)
        }
      }
    })
  } else {
    if (array) {
      temp.push(array)
    }
  }
  return temp
}
